package com.framework.controller.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.framework.annotation.SystemLog;
import com.framework.controller.index.BaseController;
import com.framework.entity.DatacenterFormMap;
import com.framework.entity.DepartmentFormMap;
import com.framework.entity.ResFormMap;
import com.framework.entity.ResUserFormMap;
import com.framework.entity.RoleFormMap;
import com.framework.entity.UserDepartmentFormMap;
import com.framework.entity.ConsoleuserFormMap;
import com.framework.entity.UserRoleFormMap;
import com.framework.entity.factory.FormmapFactory;
import com.framework.entity.view.OrderFuncDatasourceViewFormMap;
import com.framework.entity.view.OrderFuncViewFormMap;
import com.framework.entity.view.UserRoleDepartmentViewFormMap;
import com.framework.entity.view.UserRoleViewFormMap;
import com.framework.entity.view.UsersourceViewFormMap;
import com.framework.plugin.PageView;
import com.framework.plugin.test.ContextHolder;
import com.framework.plugin.token.Token;
import com.framework.util.Common;
import com.framework.util.GetDataFromOtherDB;
import com.framework.util.PasswordHelper;
import com.framework.util.TreeObject;
import com.framework.util.TreeUtil;

/**
 * 
 * @author framework 2015-11-19
 * @Email: g5874589652@126.com
 * @version 4.0v
 */
@Controller
@RequestMapping("/consoleuser/")
public class ConsoleuserController extends BaseController {
	List<ResFormMap> res = null;

	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		res = findByRes();
		model.addAttribute("res", getButtomM(res));
		return Common.BACKGROUND_PATH + "/system/consoleuser/list";
	}

	@RequestMapping("saleRecordList")
	public String saleRecordListUI(Model model) throws Exception {
		res = findByRes();
		model.addAttribute("res", getButtomM(res));
		return Common.BACKGROUND_PATH + "/system/consoleuser/saleRecordList";
	}

	@ResponseBody
	@RequestMapping("getButton")
	public String getButton() throws Exception {

		return getButtomB(res);
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage(String draw, String length, String start) throws Exception {
		UserRoleDepartmentViewFormMap userRoleDepartmentViewFormMap = new UserRoleDepartmentViewFormMap();
		userRoleDepartmentViewFormMap.put("$orderby", getorder());
		userRoleDepartmentViewFormMap.put("$search", getsearch());
		userRoleDepartmentViewFormMap.put("visible", 0);
		userRoleDepartmentViewFormMap.put("keyCloumn",  getKeyCloumn());
		userRoleDepartmentViewFormMap = toFormMap(userRoleDepartmentViewFormMap, draw, length, start);
		pageView = userRoleDepartmentViewFormMap.findByPage_Names(pageView);
		return pageView;
	}

	/**
	 * 个人销售中心，的个人记录
	 * 
	 * @author 李品良 创建时间：2016年9月20日 下午4:28:02
	 * @param draw
	 * @param length
	 * @param start
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("saleRecord")
	public PageView saleRecord(String draw, String length, String start) throws Exception {
		OrderFuncDatasourceViewFormMap formMap = FormmapFactory.getBeanFormMap(OrderFuncDatasourceViewFormMap.class);
		ConsoleuserFormMap consoleuserFormMap = (ConsoleuserFormMap) Common.findUserSession();
		String accountName = consoleuserFormMap.getStr("accountName");
		formMap.put("df_creater", accountName);
		formMap.put("$orderby", "order by df_update_time desc");
		formMap.put("$search", getsearch());
		formMap.put("keyCloumn",  getKeyCloumn());
		formMap = toFormMap(formMap, draw, length, start);
		pageView=formMap.findByPage_Names(pageView);
		return pageView;
	}

	@RequestMapping("saleInfoUI")
	public String saleInfoUI(Model model) throws Exception {
		OrderFuncDatasourceViewFormMap formMap = getMapformDataMap(OrderFuncDatasourceViewFormMap.class,
				getMapFromRequest());
		formMap = formMap.findbyFrist();
		model.addAttribute("formMap", formMap);
		return Common.BACKGROUND_PATH + "/system/consoleuser/saleInfoUI";
	}

	@RequestMapping("showInfoUI")
	public String showInfoUI(Model model) throws Exception {
		// 新增用户时寻找本用户能给新用户设定哪些上司
		UserRoleViewFormMap userRoleViewFormMap = new UserRoleViewFormMap();
		String id = Common.findUserSessionId();
		userRoleViewFormMap.put("id", id);

		userRoleViewFormMap = userRoleViewFormMap.findbyFrist();

		int level = userRoleViewFormMap.getInt("rl_id");
		RoleFormMap roleFormMap = new RoleFormMap();
		roleFormMap.put("where", "id>" + --level);
		List<RoleFormMap> list = roleFormMap.findByWhere();

		List<DepartmentFormMap> departmentlist = new DepartmentFormMap().findByWhere();

		model.addAttribute("rolelist", list);
		model.addAttribute("departmentlist", departmentlist);

		return Common.BACKGROUND_PATH + "/system/consoleuser/showInfoUI";
	}

	@RequestMapping("addUI")
	@Token(save = true)
	public String addUI(Model model) throws Exception {
		// 新增用户时寻找本用户能给新用户设定哪些上司
		UserRoleViewFormMap userRoleViewFormMap = new UserRoleViewFormMap();
		String id = Common.findUserSessionId();
		userRoleViewFormMap.put("id", id);

		userRoleViewFormMap = userRoleViewFormMap.findbyFrist();

		int level = userRoleViewFormMap.getInt("rl_id");
		RoleFormMap roleFormMap = new RoleFormMap();
		roleFormMap.put("where", "id>" + --level);
		List<RoleFormMap> list = roleFormMap.findByWhere();

		List<DepartmentFormMap> departmentlist = new DepartmentFormMap().findByWhere();

		model.addAttribute("rolelist", list);
		model.addAttribute("departmentlist", departmentlist);

		return Common.BACKGROUND_PATH + "/system/consoleuser/add";
	}

	@ResponseBody
	@RequestMapping("addEntity")
	@Token(remove = true)
	@SystemLog(module = "系统管理", methods = "用户管理-新增用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String addEntity(String txtGroupsSelect) throws Exception {
		String sessionid = Common.findUserSessionId();
		if (sessionid != null) {
			ConsoleuserFormMap userFormMap = getFormMap(ConsoleuserFormMap.class);
			userFormMap.put("tel", userFormMap.get("cellphone"));
			PasswordHelper passwordHelper = new PasswordHelper();
			userFormMap.put("password", "123456789");
			passwordHelper.encryptPassword(userFormMap);
			userFormMap.put("addid", sessionid);

			String department_id = userFormMap.getStr("department_id");
			userFormMap = userFormMap.save();
			// 插入角色关系
			UserRoleFormMap userRoleFormMap = new UserRoleFormMap();
			userRoleFormMap.put("role_id", userFormMap.get("role_id"));
			userRoleFormMap.put("user_id", userFormMap.get("id"));

			// 插入部门关系
			UserDepartmentFormMap userDepartmentFormMap = new UserDepartmentFormMap();
			userDepartmentFormMap.put("user_id", userFormMap.get("id"));
			userDepartmentFormMap.put("department_id", department_id);
			userDepartmentFormMap.save();

			userRoleFormMap.save();
			// 插入权限
			ResFormMap.mapper().addUserResourcess(userFormMap.getStr("id"), userFormMap.getStr("role_id"));

		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("addUserRes")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理/组管理-修改权限") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String addUserRes(Model model, HttpServletRequest httpServletRequest) throws Exception {
		ResourcesController resourcesController = new ResourcesController();
		return resourcesController.addUserRes(model, httpServletRequest);
	}

	/**
	 * 权限分配页面
	 * 
	 * @author framework Email：g5874589652@126.com date：2015-4-14
	 * @param model
	 * @return
	 */
	@RequestMapping("permissions")
	public String permissions(Model model) {
		HashMap<String, Object> hashMap = getMapFromRequest();
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		String userId = hashMap.get("id").toString();
		session.setAttribute("userId", userId);
		session.setAttribute("resFormMap.id", userId);

		ResourcesController resourcesController = new ResourcesController();
		resourcesController.permissions(model);

		return Common.BACKGROUND_PATH + "/system/consoleuser/permissions";
	}

	@ResponseBody
	@RequestMapping("findRes")
	public List<ResFormMap> findUserRes(Model model, HttpServletRequest httpServletRequest) {
		ResourcesController resourcesController = new ResourcesController();
		List<ResFormMap> rs = resourcesController.findUserRes(model, httpServletRequest);
		return rs;
	}

	@ResponseBody
	@RequestMapping("addEntityManual")
	@SystemLog(module = "系统管理", methods = "用户管理-新增用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String addEntityManual(String txtGroupsSelect, ConsoleuserFormMap userFormMap) throws Exception {
		String sessionid = Common.findUserSessionId();
		if (sessionid != null) {
			userFormMap.put("txtGroupsSelect", txtGroupsSelect);
			PasswordHelper passwordHelper = new PasswordHelper();
			userFormMap.put("password", "123456789");
			passwordHelper.encryptPassword(userFormMap);
			SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			userFormMap.put("createTime", time.format(new Date()));
			userFormMap.put("addid", sessionid);
			userFormMap.save();
			if (!Common.isEmpty(txtGroupsSelect)) {
				String[] txt = txtGroupsSelect.split(",");
				UserRoleFormMap UserRoleFormMap = null;
				for (String roleId : txt) {
					UserRoleFormMap = new UserRoleFormMap();
					UserRoleFormMap.put("userId", userFormMap.get("id"));
					UserRoleFormMap.put("roleId", roleId);
					UserRoleFormMap.save();
				}
			}
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("deleteEntity")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-删除用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() throws Exception {
		String[] ids = getParaValues("ids");

		for (String id : ids) {
			new UserRoleFormMap().deleteByAttribute("user_id", id);
			new ResUserFormMap().deleteByAttribute("userId", id);
			new ConsoleuserFormMap().deleteByAttribute("id", id);
			new UserDepartmentFormMap().deleteByAttribute("user_id", id);
		}
		return "success";
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			model.addAttribute("consoleuserFormMap", new ConsoleuserFormMap().findById(id));
		}
		return Common.BACKGROUND_PATH + "/system/consoleuser/edit";
	}

	@ResponseBody
	@RequestMapping("editEntity")
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity() throws Exception {
		ConsoleuserFormMap formMap = getFormMap(ConsoleuserFormMap.class);
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		formMap.put("updateTime", time.format(new Date()));
		formMap.update();
		return "success";
	}

	@ResponseBody
	@RequestMapping("leave")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String leaveFun(String txtGroupsSelect) throws Exception {
		ConsoleuserFormMap userFormMap = new ConsoleuserFormMap();
		String[] ids = getParaValues("ids");
		if (ids[0] != null) {
			userFormMap.put("id", ids[0]);
			userFormMap.put("locked", 0);
			userFormMap.update();
		}
		return "success";
	}

	// unfreeze解除账号冻结
	@ResponseBody
	@RequestMapping("unfreeze")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String unfreezeFun(String txtGroupsSelect) throws Exception {
		ConsoleuserFormMap userFormMap = new ConsoleuserFormMap();
		String[] ids = getParaValues("ids");
		if (ids[0] != null) {
			userFormMap.put("id", ids[0]);
			userFormMap.put("locked", 1);
			userFormMap.update();
		}
		return "success";
	}

	// 密码修改
	@RequestMapping("updatePassword")
	public String updatePassword(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/consoleuser/updatePassword";
	}

	// 保存新密码
	@RequestMapping("editPassword")
	@ResponseBody
	@Transactional // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改密码") // 凡需要处理业务逻辑的.都需要记录操作日志
	public Map<String, Object> editPassword() throws Exception {
		// 当验证都通过后，把用户信息放在session里
		ConsoleuserFormMap consoleuserFormMap = getFormMap(ConsoleuserFormMap.class);
		Subject consoleuser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(consoleuser.getPrincipal().toString(),
				consoleuserFormMap.getStr("oldpassword"));
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			consoleuser.login(token);
			consoleuserFormMap.put("id", Common.findUserSessionId());
			consoleuserFormMap.put("accountName", consoleuser.getPrincipal());
			consoleuserFormMap.put("password", consoleuserFormMap.get("newpassword"));
			// 这里对修改的密码进行加密
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(consoleuserFormMap);
			consoleuserFormMap.update();
			map.put("results", "success");
			map.put("messages", "密码修改成功!");
		} catch (LockedAccountException lae) {
			token.clear();
			map.put("results", "error");
			map.put("messages", "用户已经被锁定不能登录，请与管理员联系！");
		} catch (AuthenticationException e) {
			token.clear();
			map.put("results", "error");
			map.put("messages", "用户或密码不正确！！");
		}
		return map;
	}

	// 验证方法
	@ResponseBody
	@RequestMapping("isExist")
	public boolean isExist(String name) {
		ConsoleuserFormMap consoleuserFormMap = getFormMap(ConsoleuserFormMap.class);
		List<ConsoleuserFormMap> list = consoleuserFormMap.findByNames();
		if (list.size() == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检验手机号码
	 * 
	 * @author 李品良 创建时间：2016年9月8日 下午5:34:25
	 * @return
	 */
	@RequestMapping("checkCellphone")
	@ResponseBody
	public boolean checkCellphone() {
		ConsoleuserFormMap consoleuserFormMap = getFormMap(ConsoleuserFormMap.class);
		String cellphone = consoleuserFormMap.getStr("cellphone");
		return Common.isCellphone(cellphone);
	}

	/**
	 * 检验邮箱
	 * 
	 * @author 李品良 创建时间：2016年9月8日 下午5:34:25
	 * @return
	 */
	@RequestMapping("checkEmail")
	@ResponseBody
	public boolean checkEmail() {
		ConsoleuserFormMap consoleuserFormMap = getFormMap(ConsoleuserFormMap.class);
		String email = consoleuserFormMap.getStr("email");
		return Common.isEmail(email);

	}

	// 修改时的验证方法
	@ResponseBody
	@RequestMapping("editisExist")
	public boolean editisExist() {
		ConsoleuserFormMap userFormMap = getFormMap(ConsoleuserFormMap.class);
		// 先根据名称去找，没有就返回true
		// 有的话就判断是不是这id的记录，如果是的话也返回true
		// 否则返回false
		List<ConsoleuserFormMap> list = userFormMap.findByAttribute("userName", userFormMap.get("userName"));
		if (list.size() == 0) {
			return true;
		} else {
			if (list.size() >= 0) {
			}
			return false;
		}
	}

}